﻿package  {
	import flash.geom.Point;
	import flash.display.BitmapData;
	import flash.geom.Rectangle;
	import flash.utils.setInterval;
	import flash.display.MovieClip;
	
	public class ObstacleController {
		
		private var runningGame:RunningGame;
		private var listOfObstacle:Array;
		private var currentObstacle:Array;
		private static const percentage:Number = 0.8;
		private var interval;
		public static const obstacleVelocity:Number = 1000;
		
		public function ObstacleController(runningGame:RunningGame) {									
			this.runningGame = runningGame;						
			initialize();
		}
		
		public function initialize():void {
			clearPooling();
			pool(this,new Hazard1BD(),10);
			pool(this,new CoinBD(),20);			
			currentObstacle = new Array();			
			interval = setInterval(createObstacle,500);
		}
		
		private function clearPooling():void {
			listOfObstacle = [];
		}
		
		private function pool(controller:ObstacleController,obstacle:BitmapData,size:Number) {
			for(var i=0;i<size;i++) {				
				listOfObstacle.push(new Obstacle(this,obstacle, runningGame));				
			}
		}
		
		public function update(elapsedTime:Number,collideFunc:Function, player:Player) {
			for (var i=0;i<currentObstacle.length;i++) {
				var obstacle = currentObstacle[i];
				obstacle.moveDown(obstacleVelocity*elapsedTime);
				if(obstacle.y > runningGame.getScreenHeight()) {
					obstacle.resetPosition();
					listOfObstacle.push(obstacle);
					currentObstacle.splice(i,1);
					i--;
				}						
				if(obstacle.intersect(player.getOriginX(), player.getOriginY(), player.getWidth(),player.getHeight())) {
					collideFunc(obstacle, player);
					//setelah tabrakan, hilangkan obstacle tersebut
					if(obstacle.getType()!=Obstacle.HAZARD) {
						obstacle.resetPosition();
						listOfObstacle.push(obstacle);
						currentObstacle.splice(i,1);
						i--;
					}
				}								
			}
		}
		
		public function render(canvasBD:BitmapData, elapsedTime:Number) {
			for each(var obstacle:Obstacle in currentObstacle) {
				canvasBD.copyPixels(obstacle.bitmapData, new Rectangle(0,0,obstacle.width, obstacle.height), new Point(obstacle.x,obstacle.y));
			}
		}
		
		private function createObstacle() {
			if(Math.random() < percentage) {
				if(listOfObstacle.length > 0) {
					var randomNum = Math.floor(Math.random()*listOfObstacle.length);
					currentObstacle.push(listOfObstacle[randomNum]);
					listOfObstacle.splice(randomNum,1);
				}
			}
		}
	}
}